package org.dtrd.modules.shop.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import org.dtrd.common.util.DateUtils;
import org.dtrd.common.util.StringUtil;
import org.dtrd.config.system.Constant;
import org.dtrd.modules.achievement.entity.bean.SigninTemplateListInfo;
import org.dtrd.modules.doctor.entity.bean.DoctorInfo;
import org.dtrd.modules.patient.entity.bean.PatientInfo;
import org.dtrd.modules.patient.entity.po.DtrdEntRdPatient;
import org.dtrd.modules.patient.service.IDtrdEntRdPatientService;
import org.dtrd.modules.shop.entity.po.DtrdEntShcRdGlucometerGet;
import org.dtrd.modules.shop.entity.po.DtrdEntShcRdOrder;
import org.dtrd.modules.shop.entity.request.GlucometerPhotoRequest;
import org.dtrd.modules.shop.mapper.DtrdEntShcRdGlucometerGetMapper;
import org.dtrd.modules.shop.service.IDtrdEntShcRdGlucometerGetService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.dtrd.modules.shop.entity.bean.GlucometerGetDetail;
import org.dtrd.modules.shop.entity.bean.GlucometerGetListInfo;
import org.dtrd.modules.shop.entity.bean.GlucometerGetListRequest;
import org.dtrd.modules.shop.entity.bean.GlucometerGetPageRequest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 血糖仪领用表 服务实现类
 * </p>
 *
 * @author xiao
 * @since 2022-06-29
 */
@DS("multi-datasource1")
@Service
public class DtrdEntShcRdGlucometerGetServiceImpl extends ServiceImpl<DtrdEntShcRdGlucometerGetMapper, DtrdEntShcRdGlucometerGet> implements IDtrdEntShcRdGlucometerGetService {

    private DtrdEntShcRdGlucometerGetMapper dtrdEntShcRdGlucometerGetMapper;
    @Autowired
    private IDtrdEntRdPatientService dtrdEntRdPatientService;

    @Override
    public List<GlucometerGetListInfo> getGlucometerGetList(GlucometerGetListRequest request) {
        LambdaQueryWrapper<DtrdEntShcRdGlucometerGet> queryWrapper = baseQueryWrapper();
        List<DtrdEntShcRdGlucometerGet> poList = list(queryWrapper);
        List<GlucometerGetListInfo> dtoList = new ArrayList<>(poList.size());
        if (!poList.isEmpty()) {
            dtoList = poList.stream().map(GlucometerGetListInfo::new).collect(Collectors.toList());
        }
        return dtoList;
    }

    @Override
    public IPage<GlucometerGetListInfo> pageGlucometerGet(GlucometerGetPageRequest request) {
        LambdaQueryWrapper<DtrdEntShcRdGlucometerGet> queryWrapper = baseQueryWrapper();
        if (request.getDoctorId() != null) {
            queryWrapper.eq(DtrdEntShcRdGlucometerGet::getDoctorId, request.getDoctorId());
        }
        if (request.getDay() != null) {

            System.out.println(wrapperDate(request.getDay(), "start"));
            System.out.println(wrapperDate(request.getDay(), "end"));
            queryWrapper.between(DtrdEntShcRdGlucometerGet::getScanTime, wrapperDate(request.getDay(), "start"), wrapperDate(request.getDay(), "end"));
        } else {
            System.out.println(wrapperDate(DateUtils.formatDate(new Date(), DateUtils.date_sdf.get().toPattern()), "start"));
            System.out.println(wrapperDate(DateUtils.formatDate(new Date(), DateUtils.date_sdf.get().toPattern()), "end"));

            queryWrapper.between(DtrdEntShcRdGlucometerGet::getScanTime, wrapperDate(DateUtils.formatDate(new Date(), DateUtils.date_sdf.get().toPattern()), "start"), wrapperDate(DateUtils.formatDate(new Date(), DateUtils.date_sdf.get().toPattern()), "end"));
        }
        IPage<DtrdEntShcRdGlucometerGet> page = new Page<>(request.getPageNum(), request.getPageSize());
        page = this.page(page, queryWrapper);

        return page.convert(po -> {
            GlucometerGetListInfo glucometerGetListInfo = new GlucometerGetListInfo(po);
            glucometerGetListInfo.setScanTimeStr(DateUtils.formatDate(po.getScanTime(), DateUtils.short_time_sdf.get().toPattern()));
            if (po.getPatientId() != null) {

                DtrdEntRdPatient patientInfo =  dtrdEntRdPatientService.getById(po.getPatientId());
                glucometerGetListInfo.setPatientName(patientInfo.getPatientsName());
            }
            return glucometerGetListInfo;
        });
    }

    private DateTime wrapperDate(String Date, String type) {
        String dateStr = Objects.equals(type, "start") ? Date + " " + "00:00:00" : Date + " " + "23:59:59";
        return DateUtil.parse(dateStr, DateUtils.datetimeFormat.get().toPattern());
    }

    @Override
    public GlucometerGetDetail getGlucometerGet(Integer dataId) {
        DtrdEntShcRdGlucometerGet dtrdEntShcRdGlucometerGet = getById(dataId);
        return Optional.ofNullable(dtrdEntShcRdGlucometerGet)
                        .map(po -> new GlucometerGetDetail().parseFromPo(po))
                        .orElse(null);
    }

    @Override
    public boolean saveOrUpdateGlucometerGet(GlucometerGetDetail dto) {
        DtrdEntShcRdGlucometerGet dtrdEntShcRdGlucometerGet = new DtrdEntShcRdGlucometerGet();
        if(dto.getDataId() == null){
            dtrdEntShcRdGlucometerGet = dtrdEntShcRdGlucometerGet.init();
        }
        dtrdEntShcRdGlucometerGet.parseFromDto(dto);
        return saveOrUpdate(dtrdEntShcRdGlucometerGet);
    }

    @Override
    public boolean removeGlucometerGet(Integer dataId) {
        return removeById(dataId);
    }

    @Override
    public boolean saveOldGlucometerPhoto(GlucometerPhotoRequest request) {
        if (request.getGlucometerGetId() == null) {
            return false;
        }
        DtrdEntShcRdGlucometerGet dtrdEntShcRdGlucometerGet = new DtrdEntShcRdGlucometerGet();
        dtrdEntShcRdGlucometerGet.setOldGlucometerImage(request.getPhotoSrc());
        // status: 1-已领取，2-已领取未上传
        dtrdEntShcRdGlucometerGet.setGetStatus(1);
        return update(dtrdEntShcRdGlucometerGet,
                Wrappers.lambdaQuery(DtrdEntShcRdGlucometerGet.class)
                        .eq(DtrdEntShcRdGlucometerGet::getDataId, request.getGlucometerGetId())
        );
    }

    @Override
    public JSONObject addGetRecord(DtrdEntShcRdOrder order, DoctorInfo doctorInfo) {
        JSONObject result = new JSONObject();
        DtrdEntShcRdGlucometerGet dtrdEntShcRdGlucometerGet = new DtrdEntShcRdGlucometerGet();
        // 1. 判断有没有领取过
        LambdaQueryWrapper<DtrdEntShcRdGlucometerGet> wrapper = Wrappers.lambdaQuery(DtrdEntShcRdGlucometerGet.class)
                .eq(DtrdEntShcRdGlucometerGet::getDoctorId, doctorInfo.getDataId())
                .eq(DtrdEntShcRdGlucometerGet::getPatientId, order.getOrderInfoUserid())
                .last("limit 1");
        DtrdEntShcRdGlucometerGet data = getOne(wrapper);
        if (data != null) {
            result.put("status", false);
            result.put("error", "该患者"+DateUtils.formatDate(data.getScanTime(), DateUtils.date_sdf.get().toPattern())+"已领取血糖仪");
            return result;
        }

        // 2. 判断是否是以旧换新
        if (order.getOrderInfoTitle().indexOf("以旧换新") != -1) {
            dtrdEntShcRdGlucometerGet.setGetStatus(2);
        } else {
            dtrdEntShcRdGlucometerGet.setGetStatus(1);
        }
        dtrdEntShcRdGlucometerGet.setDoctorId(doctorInfo.getDataId());
        dtrdEntShcRdGlucometerGet.setPatientId(order.getOrderInfoUserid());
        dtrdEntShcRdGlucometerGet.setCreateTime(new Date());
        dtrdEntShcRdGlucometerGet.setOrderId(order.getDataId());
        dtrdEntShcRdGlucometerGet.setScanTime(new Date());
        boolean save = save(dtrdEntShcRdGlucometerGet);
        result.put("status", save);
        result.put("error", save ? "领取成功" : "领取失败");
        return result;
    }

    private LambdaQueryWrapper<DtrdEntShcRdGlucometerGet> baseQueryWrapper() {
        return Wrappers.lambdaQuery(DtrdEntShcRdGlucometerGet.class)
                        .eq(DtrdEntShcRdGlucometerGet::getIsDel, 0);
    }

    private LambdaUpdateWrapper<DtrdEntShcRdGlucometerGet> baseUpdateWrapper() {
        return Wrappers.lambdaUpdate(DtrdEntShcRdGlucometerGet.class)
                        .eq(DtrdEntShcRdGlucometerGet::getIsDel, 0);
    }
}
